package com.cryann.mqttserver.mqttProcess;

import com.cryann.mqttserver.modle.MqttMessageStore;
import com.cryann.mqttserver.modle.MqttSendMessage;
import com.cryann.mqttserver.service.MqttSubject;
import com.cryann.mqttserver.service.MsgStoreService;
import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author cRyann
 * @date 2018/12/24 0024 09:44
 * @description: 另类处理PUBREL
 * //TODO 发送PUBLISH
 * //TODO 处理PUBCOMP
 */
@Component
@Slf4j
@ProcessType(MqttMessageType.PUBREL)
public class Pubrel implements BasicProcess<MqttMessage> {

    @Autowired
    MqttMessageStore mqttMessageStore;
    @Autowired
    MqttSubject mqttSubject;
    @Autowired
    MsgStoreService msgStoreService;

    @Override
    public void process(Channel ctx, MqttMessage message) {

        // 获取Publish的message
        MqttMessageIdVariableHeader header = (MqttMessageIdVariableHeader) message.variableHeader();
        MqttSendMessage msg = msgStoreService.peekMsg(ctx);
        // 发送PUBLISH
        mqttSubject.publicSub(msg);

        // 应答 处理PUBCOMP
        MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBCOMP, false, message.fixedHeader().qosLevel(), false, 2);
        MqttMessageIdVariableHeader variableHeader = MqttMessageIdVariableHeader.from(header.messageId());
        MqttMessage pubAck = MqttMessageFactory.newMessage(fixedHeader, variableHeader, null);
        ctx.writeAndFlush(pubAck);

    }
}
